//Page Object
// 获取应用实例
const app = getApp<IAppOption>()
const { request} = require('../../utils/request')
const { markReg } = require('../../utils/util')
enum currentTempEnum {
  'riji',
  'shige',
  'shuxin'
}
const rowWordNum = 9

Page({
  data: {
    loading:true,
    recordId:'',
    current: 0,  // 0 是日记 1是诗歌  2 书信
    currentTemplateCode:'riji',
    templateList:[
      {
        title:'',
        content:'',
        templateCode:'riji'
      },
      {
        title:'',
        content:'',
        templateCode:'shige'
      },
      {
        title:'',
        content:'',
        templateCode:'shuxin'
      }
    ],
    status:'',  // 是否分享过，1为未分享 2为已分享
    shareChannel:2
  },
  //options(Object)
  onLoad: function(options){
    
    if(options && options.id){
      this.setData({
        recordId:options.id,
        shareChannel: options.shareChannel || 2
      })
      console.log('this.data:',this.data)
      this.initCurrent(options.id)
      this.getDiaryData()
    }else {
      wx.showModal({
        content:'记录id不存在',
        confirmText:'返回上一页',
        showCancel:false,
        success:()=>{
          wx.navigateBack({
            delta:1
          })
        }
      })
    }
    
    
    
  },
  mainTouchMove(event:any){
    event.preventDefault()
    return false
  },

  resolveLoadingStatus(){
    setTimeout(()=>{
      this.setData({
        loading:false
      })
    },100)
  },
  initCurrent(recordId:string){
    // 查询用户最后一次分享信息
    let that = this
    request({
      url:`/records/${recordId}/last-share`,
      success:(data:any)=>{
        
        // 最后一次分享的templateCode
        if(data){
          let templateCode = data.templateCode || 'riji'
          console.log('/last-share templateCode:',templateCode)
          let current = currentTempEnum[templateCode]
          console.log('current:',current)
          that.setData({
            current:currentTempEnum[templateCode],
            currentTemplateCode:templateCode,
          },()=>{
            that.resolveLoadingStatus()
          })
        }else {
          that.resolveLoadingStatus()
        }
      },
 
    })
  },
  getDiaryData(){
    let diaryData = wx.getStorageSync('/index/templateData') || { title:'',content:''}
    // 日记
    diaryData.templateCode = 'riji'
    let templateList = this.data.templateList
    templateList[0] = diaryData
    
    this.setData({
      templateList
    })
    this.getTemplateData()
    
    
  },
  getTemplateData(){
    // 获取诗歌模版内容
    request({
      url:`/records/${this.data.recordId}/template-contents`,
      method:'GET',
      success:(data:any)=>{
        // console.log('template-contents data:',data)
        if(data && data.length > 0){
          // clearInterval(reqTemplateDataTimeHandler)
          let templateList = this.data.templateList
          templateList = [templateList[0],...data]
          templateList.forEach((item:any)=>{
            if(item.templateCode ==='shuxin'){
              let contentList = [] 
              let content = item.content.replace(/\n+|\s+/g,'')
              
              for(let i=0; i < content.length;){
                let str = content.slice(i,i+rowWordNum)
                i+=rowWordNum
                // 截取的字符串中有标点符号,那就再截取1个
                let matchList = str.match(markReg)
                if(matchList){
                  // 标点符号的数量
                  let mLen = matchList.length
                  // 每2个标点符号算1个汉字
                  let halfLen = Math.ceil(mLen/2)

                  let nextChar = content.slice(i,i+halfLen)
                  str+=nextChar
                  i+=halfLen
                }
                // 如果下一行开头是标点符号，那就再截取1个
                let nextChar = content[i] || ''
                if(markReg.test(nextChar)){
                  str+=nextChar
                  i++
                }
                contentList.push(str)
              }
              item.content = contentList
            }else if(item.templateCode ==='shige'){
              item.contLines = item.content.split('\n').length
              item.content = item.content.trim()
            }else {
              item.content = item.content.trim()
            }
            
          })
          
          this.setData({
            templateList,
          })
          
        }    
      }
    })
  },

  swiperChange(event:any){
    let {current} = event.detail
    // console.log('current:',current)
    this.setData({
      current,
      currentTemplateCode:this.data.templateList[current].templateCode
    })
  },
  getShareData(){
    let that = this
    let userInfo = wx.getStorageSync('userInfo')
    let userId = (userInfo && userInfo.id) || ''
    return new Promise((resolve)=>{
      request({
        url:'/record-share',
        method:'POST',
        data:{
          recordId: this.data.recordId,
          templateCode:this.data.currentTemplateCode
        },
        success:(data:any)=>{
          let title = ''
          let current = that.data.current
          if(current === 0){
            title = '我记了一篇日记，快来看看吧'
          } else if(current ===1){
            title = '我作了一首诗，快来看看吧'
          } else if (current === 2){
            title = '我写了一封信，快来看看吧'
          }
          
          resolve({
            title: title,
            path:'/pages/share/share?inviteUserId='+userId+'&shareChannel='+ that.data.shareChannel + '&id='+data.id,
          })    
        }
      })
    })
  },
  onShareAppMessage(){
    return {
      ...app.getDefaultShareData(),
      promise: this.getShareData()
    }
  },
  onShareTimeline(){
    return {
      ...app.getDefaultShareData(),
      promise: this.getShareData()
    }
  },
});